package org.dromara.vehicle.modules.gaoDe.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.dto.AreaDto;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.service.AreaService;
import org.dromara.vehicle.modules.gaoDe.domain.GdPoi;
import org.dromara.vehicle.modules.gaoDe.domain.vo.GdTipVo;
import org.dromara.vehicle.modules.gaoDe.mapper.GdPoiMapper;
import org.dromara.vehicle.modules.gaoDe.service.GdPoiService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 高德poi类型(GdPoi)表服务实现类
 *
 * @author ckk
 * @since 2025-08-16 09:35:13
 */
@RequiredArgsConstructor
@Service
public class GdPoiServiceImpl extends ServiceImpl<GdPoiMapper, GdPoi> implements GdPoiService {

    private final GdPoiMapper baseMapper;
    private final AreaService areaService;

    @Override
    public List<GdTipVo> tips(String keyWord, String location) {
        String url = "https://restapi.amap.com/v3/assistant/inputtips?keywords=" + keyWord + "&location=" + location + "&key=" + "5b32b027ac88064d32aff37c822c73ff";
        String data = HttpUtil.get(url);
        JSONObject jsonObject = JSONUtil.parseObj(data);
        // 1：成功；0：失败
        if (jsonObject.getInt("status") == 0) {
            throw new ServiceException("API调用失败: " + jsonObject.getStr("info"));
        }
        List<GdTipVo> tips = jsonObject.getJSONArray("tips").toList(GdTipVo.class);
        if (CollUtil.isNotEmpty( tips)) {
            Set<String> codes = tips.stream().map(GdTipVo::getTypecode).collect(Collectors.toSet());
            Map<String, String> codeMap = this.lambdaQuery().in(GdPoi::getTypeCode, codes).list().stream().collect(Collectors.toMap(GdPoi::getTypeCode, GdPoi::getSubCategory));
            tips.forEach(tip -> tip.setTypeLabel(codeMap.getOrDefault(tip.getTypecode(), "")));

            List<String> adcodes = tips.stream().map(GdTipVo::getAdcode).map(o-> StrUtil.padAfter(o, 12, "0")).collect(Collectors.toList());
            Map<String, String> araeMap = areaService.getAreaNamesByIds(adcodes).stream().collect(Collectors.toMap(AreaDto::getAdcode, AreaDto::getAreaName));
            tips.forEach(tip -> tip.setAreaName(araeMap.getOrDefault(tip.getAdcode(), "")));
        }

        return tips;
    }

}

